package funcs

import (
	"encoding/json"
	"strconv"
	"time"

	"github.com/gorilla/websocket"
	"github.com/wonderivan/logger"
)

// Source web_park|web_enterprise|app
func FindUsers(UserId string) []*Client {
	var conn []*Client
	if Manager.Clients[UserId] != nil {
		conn = Manager.Clients[UserId]
	}
	return conn
}

// Source web_park|web_enterprise|app
func FindUser(UserId string, Source string) *Client {
	var conn *Client
	if Manager.Clients[UserId] != nil {
		for _, co := range Manager.Clients[UserId] {
			if Source == "" {
				if co.UserId == UserId {
					return co
				}
			} else {
				if co.IpSource == Source && co.UserId == UserId {
					return co
				}
			}

		}
	}
	return conn
}

// Read 读取客户端发送过来的消息
func (c *Client) Read() {
	// 出现故障后把当前客户端注销
	defer func() {
		_ = c.Socket.Close()
		Manager.UnRegister <- c
	}()
	for {
		_, data, err := c.Socket.ReadMessage()
		if err != nil {
			logger.Error(err.Error(), data)
			break
		}
		var _msg WsMessage

		err = json.Unmarshal(data, &_msg)

		if err != nil {
			logger.Error("err", err.Error(), string(data), "client_id", c.UserId)
			break
		}

		switch _msg.Type {
		case Heart:
			// 如果是心跳监测消息（利用心跳监测来判断对应客户端是否在线）
			resp, _ := json.Marshal(&WsMessage{Type: 6, Data: "pong"})
			c.Start = time.Now() // 重新刷新时间
			c.Send <- resp
		case User_len:
			// 获取在线人数
			count := len(Manager.Clients)
			resp, _ := json.Marshal(&WsMessage{Type: 1, Data: "当前在线人数为:" + strconv.Itoa(count), UserId: "系统消息"})
			c.Send <- resp
		case History:
			// 获取消息历史记录
			// sql := fmt.Sprintf("select * from %s_msg", c.UserId)
			// resu, _ := mysqlA.CusSql.QuerySql(sql)
			// resp, _ := json.Marshal(&WsMessage{Type: History, Data: resu, Business: _msg.Business})
			// c.Send <- resp
		case Mass:
			// 群发送文本消息
			resp, _ := json.Marshal(&WsMessage{Type: Mass, Data: _msg.Data})
			Manager.Broadcast <- resp

		case Singe:
			// 单独发送文本
			mess := map[string]interface{}{
				"id":          c.UserId,
				"name":        c.Name,
				"headimg":     c.Headimg,
				"person_sign": c.Person_sign,
				"data":        _msg.Data,
			}
			resp, _ := json.Marshal(&WsMessage{Type: Singe, Data: mess})
			var conn = FindUsers(_msg.UserId)
			for _, cn := range conn {
				cn.Send <- resp
			}
		}
	}
}

// Write 把对应消息写回客户端
func (c *Client) Write() {
	defer func() {
		_ = c.Socket.Close()
		Manager.UnRegister <- c
	}()
	ticker := time.NewTicker(1 * time.Second)
	for range ticker.C {
		msg, ok := <-c.Send
		if !ok {
			// 没有消息则发送空响应
			err := c.Socket.WriteMessage(websocket.CloseMessage, []byte{})
			if err != nil {
				logger.Error(err.Error())
				return
			}
			return
		}
		err := c.Socket.WriteMessage(websocket.TextMessage, msg)

		if err != nil {
			logger.Error(err.Error())
			return
		}
	}

}
